<template>
  <view :class="theme">
    <view class="m-30 b-rounded-16 overflow-hidden">
      <label class="bg-4 mb-2 p-30">
        <text class="text-28" style="width: 120rpx;">收货人</text>
        <input v-model="formData.name.value" class="flex-1 ml-80 text-28" type="text" maxlength="12"
          placeholder="请输入收货人姓名" />
      </label>
      <label class="bg-4 mb-2 p-30">
        <text class="text-28" style="width: 120rpx;">联系电话</text>
        <input v-model="formData.phoneNumber.value" class="flex-1 ml-80 text-28" type="number" maxlength="11"
          placeholder="请输入联系电话" />
      </label>
      <picker class="bg-4 mb-2 p-30" mode="multiSelector" :range="range" range-key="label" @change="changeArea"
        @columnchange="columnChange">
        <label>
          <text class="text-28" style="width: 120rpx;">所在地区</text>
          <text :class="[formData.area.value ? '' : 'color-8', 'flex-1 ml-80 text-28']">
            {{ formData.area.value || "请选择省、市、区" }}
          </text>
          <uv-icon size="32" color="#999" name="arrow-down" />
        </label>
      </picker>
      <view class="flex-row bg-4 ai-start p-30 mb-2">
        <text class="text-28" style="width: 120rpx;">详细地址</text>
        <textarea class="flex-1 ml-80 text-28 h-100" v-model="formData.address.value" placeholder="请输入详细地址" maxlength="50"
          placeholder-class=" text-28" />
      </view>
      <label class="bg-4 p-30">
        <switch :checked="!!formData.isDefault.value" type="checkbox" :color="$config.COLOR_3" @change="setDefault" />
        <text class="color-subtitle">默认地址</text>
      </label>
    </view>

    <button @click="submit" hover-class="op-[0.6]" class="bg-5 color-15 text-32 m-30 b-rounded-50"
      style="line-height: 88rpx;">保存</button>
  </view>
</template>

<script lang="ts" setup>
import { useMapState } from "@/common/libs/store";
import area from "@/static/server/json/area.json";
import { reactive, computed } from "vue";
import { debounce, pickObjectProperty, sleep } from "@/common/libs/utils";
import { onLoad } from "@dcloudio/uni-app";

const { $config = {} } = getApp().globalData || {};

const { theme } = useMapState(["theme"]);
const rangeIndex = reactive([0, 0, 0]);
const range = computed(() => [
  area.map(item => pickObjectProperty(["pid", "value", "label"], item)),
  area[rangeIndex[0]].children.map(item => pickObjectProperty(["pid", "value", "label"], item)),
  area[rangeIndex[0]].children[rangeIndex[1]].children.map(item => pickObjectProperty(["pid", "value", "label"], item))
]);
const columnChange = ({ detail }: any) => {
  rangeIndex[detail.column] = detail.value;
}

const formData = reactive({
  id: {
    value: 0,
    field: "id",
  },
  name: {
    value: "",
    field: "name",
    rule: /^[\u4E00-\u9FA5a-zA-Z0-9 ]{1,10}$/,
    errorMessage: "收货人姓名输入不合法",
  },
  phoneNumber: {
    value: "",
    field: "mobile",
    rule: /^1[0-9]{10}$/,
    errorMessage: "手机号码输入有误",
  },
  area: {
    value: "",
    id: "",
    field: "area_text",
    rule: /^.+$/,
    errorMessage: "请选择所在地区",
  },
  address: {
    value: "",
    field: "remark",
    rule: /^[\u4E00-\u9FA5a-zA-Z0-9 -]{1,60}$/,
    errorMessage: "详细地址输入不合法",
  },
  isDefault: {
    value: 0,
    field: "is_default",
    rule: /^[01]$/,
  }
});

onLoad(({ id }: any) => {
  if (!id) {
    uni.setNavigationBarTitle({ title: "添加地址" });
    return;
  }

  uni.request({
    url: "/myAddressDetails",
    data: { address_id: id },
    success({ data }: any) {
      formData.id.value = data.id;
      formData.address.value = data.remark || "";
      formData.name.value = data.name || "";
      formData.phoneNumber.value = data.mobile || "";
      formData.area.value = data.area_text;
      formData.area.id = [data.province, data.city, data.county].join(",");
      formData.isDefault.value = +data.is_default;
    }
  });
});

const setDefault = ({ detail }: any) => {
  formData.isDefault.value = +detail.value;
}

const changeArea = () => {
  const result = rangeIndex.map((item, index) => range.value[index][item]);

  formData.area.id = result.map(item => item.value).join(",");
  formData.area.value = result.map(item => item.label).join(" ");
}

const submit = debounce(() => {
  const data: any = {},
    verification = (<Array<keyof typeof formData>>Object.keys(formData)).every(key => {
      const { value, field, errorMessage, rule } = formData[key] as any;
      if (errorMessage && !rule.test(String(value))) {
        uni.showToast({ title: errorMessage, icon: "none" });
        return false;
      }

      field && (data[field] = value);
      return true;
    });
  if (!verification) return;

  const [province, city, county] = formData.area.id.split(",");
  uni.request({
    url: "/saveAddress",
    data: {
      ...data,
      province, city, county,
    },
    success: async () => {
      uni.showToast({ title: "已保存", duration: 1200 });
      await sleep(1.2);
      uni.navigateBack();
    }
  })
});

</script>

<style lang="scss" scoped>
::v-deep {
  button[disabled] {
    opacity: 0.6;
  }

  switch {
    transform: scale(0.7);

    .wx-checkbox-input,
    .uni-checkbox-input {

      &:empty,
      &.wx-checkbox-input-checked,
      &.uni-checkbox-input-checked {
        border-color: $uni-bg-color-grey;
        background-color: transparent;
      }

      &:not(:empty) {
        border-color: transparent;
        background: $uni-bg-color-primary;
      }

      border-width: 2px;
      border-radius: 50%;
    }

    &:not([disabled]) {

      .wx-checkbox-input:hover,
      .uni-checkbox-input:hover {
        border-color: $uni-color-primary;
      }
    }
  }
}
</style>